package services

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonpayModels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
)

// GetIssuingHistoryList 查询卡片开卡销卡的收费记录明细
func GetIssuingHistoryList(ctx context.Context, client *photonpay.PhotonPayClient, params photonpayModels.IssuingHistoryQueryParams) (*photonpayModels.IssuingHistoryListResponse, error) {
	// 如果请求的页大小大于500，我们需要多次请求并合并结果
	if params.PageSize > 500 {
		allRecords := make([]photonpayModels.IssuingHistoryInfo, 0)
		currentPage := int64(1)
		remainingSize := params.PageSize
		pageSize := int64(500)

		// 如果没有指定时间范围，使用当前时间作为结束时间
		endTime := params.CreatedAtEnd
		if endTime == "" {
			endTime = time.Now().Format("2006-01-02 15:04:05")
		}

		// 记录最后一条数据的时间，用于下一次查询
		var lastRecordTime string

		for remainingSize > 0 {
			// 计算当前请求的页大小
			currentPageSize := pageSize
			if remainingSize < pageSize {
				currentPageSize = remainingSize
			}

			// 构建查询参数
			query := url.Values{}
			query.Set("pageIndex", fmt.Sprintf("%d", currentPage))
			query.Set("pageSize", fmt.Sprintf("%d", currentPageSize))
			if params.MatrixAccount != "" {
				query.Set("matrixAccount", params.MatrixAccount)
			}
			if params.CardID != "" {
				query.Set("cardId", params.CardID)
			}
			if params.CardFormFactor != "" {
				query.Set("cardFormFactor", params.CardFormFactor)
			}
			if params.Status != "" {
				query.Set("status", params.Status)
			}
			if params.CreatedAtStart != "" {
				query.Set("createdAtStart", params.CreatedAtStart)
			}
			// 如果有上一次查询的最后一条数据时间，使用它作为下一次查询的开始时间
			if lastRecordTime != "" {
				query.Set("createdAtStart", lastRecordTime)
			}
			query.Set("createdAtEnd", endTime)

			path := "/vcc/openApi/v4/pagingIssuingHistory?" + query.Encode()
			resp, err := client.Get(ctx, path)
			if err != nil {
				return nil, fmt.Errorf("get issuing history list failed: %v", err)
			}

			var result photonpayModels.IssuingHistoryListResponse
			if err := json.Unmarshal(resp, &result); err != nil {
				return nil, fmt.Errorf("unmarshal response failed: %v", err)
			}

			if result.Code != "0000" {
				return nil, fmt.Errorf("get issuing history list failed: %s", result.Msg)
			}

			// 如果没有数据返回，说明已经查询完毕
			if len(result.Data) == 0 {
				break
			}

			// 记录最后一条数据的时间
			lastRecordTime = result.Data[len(result.Data)-1].CreatedAt

			// 添加数据到结果集
			allRecords = append(allRecords, result.Data...)

			// 更新剩余需要查询的数量
			remainingSize -= int64(len(result.Data))

			// 如果返回的数据量小于请求的数量，说明已经没有更多数据了
			if int64(len(result.Data)) < currentPageSize {
				break
			}

			// 更新页码
			currentPage++
		}

		// 计算分页
		start := (params.PageIndex - 1) * params.PageSize
		end := start + params.PageSize
		if start >= int64(len(allRecords)) {
			start = int64(len(allRecords))
		}
		if end > int64(len(allRecords)) {
			end = int64(len(allRecords))
		}

		// 返回分页后的结果
		return &photonpayModels.IssuingHistoryListResponse{
			Code:      "0000",
			Msg:       "success",
			Data:      allRecords[start:end],
			PageIndex: params.PageIndex,
			PageSize:  params.PageSize,
			Total:     int64(len(allRecords)),
		}, nil
	}

	// 如果页大小小于等于500，直接发送请求
	query := url.Values{}
	if params.PageIndex > 0 {
		query.Set("pageIndex", fmt.Sprintf("%d", params.PageIndex))
	}
	if params.PageSize > 0 {
		query.Set("pageSize", fmt.Sprintf("%d", params.PageSize))
	}
	if params.MatrixAccount != "" {
		query.Set("matrixAccount", params.MatrixAccount)
	}
	if params.CardID != "" {
		query.Set("cardId", params.CardID)
	}
	if params.CardFormFactor != "" {
		query.Set("cardFormFactor", params.CardFormFactor)
	}
	if params.Status != "" {
		query.Set("status", params.Status)
	}
	if params.CreatedAtStart != "" {
		query.Set("createdAtStart", params.CreatedAtStart)
	}
	if params.CreatedAtEnd != "" {
		query.Set("createdAtEnd", params.CreatedAtEnd)
	}
	path := "/vcc/openApi/v4/pagingIssuingHistory"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get issuing history list failed: %v", err)
	}

	var result photonpayModels.IssuingHistoryListResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		return nil, fmt.Errorf("get issuing history list failed: %s", result.Msg)
	}

	return &result, nil
}

// GetRechargeCardFundsDetailList 查询常规卡资金明细
func GetRechargeCardFundsDetailList(ctx context.Context, client *photonpay.PhotonPayClient, params photonpayModels.VccTradeOrderQueryParams) (*photonpayModels.VccTradeOrderListResponse, error) {
	query := url.Values{}
	if params.PageIndex > 0 {
		query.Set("pageIndex", fmt.Sprintf("%d", params.PageIndex))
	}
	if params.PageSize > 0 {
		query.Set("pageSize", fmt.Sprintf("%d", params.PageSize))
	}
	if params.MemberID != "" {
		query.Set("memberId", params.MemberID)
	}
	if params.MatrixAccount != "" {
		query.Set("matrixAccount", params.MatrixAccount)
	}
	if params.CreatedAtStart != "" {
		query.Set("createdAtStart", params.CreatedAtStart)
	}
	if params.CreatedAtEnd != "" {
		query.Set("createdAtEnd", params.CreatedAtEnd)
	}
	if params.CardID != "" {
		query.Set("cardId", params.CardID)
	}
	if params.CardType != "" {
		query.Set("cardType", params.CardType)
	}
	if params.CardFormFactor != "" {
		query.Set("cardFormFactor", params.CardFormFactor)
	}
	if params.RequestID != "" {
		query.Set("requestId", params.RequestID)
	}
	if params.TransactionID != "" {
		query.Set("transactionId", params.TransactionID)
	}
	if params.TransactionType != "" {
		query.Set("transactionType", params.TransactionType)
	}
	if params.Status != "" {
		query.Set("status", params.Status)
	}

	// 使用充值卡资金明细的API端点
	path := "/vcc/openApi/v4/pagingRechargeCardFundsDetail"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get recharge card funds detail list failed: %v", err)
	}

	var result photonpayModels.VccTradeOrderListResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		return nil, fmt.Errorf("get recharge card funds detail list failed: %s", result.Msg)
	}

	// 获取所有卡片的ID
	cardIDs := make([]string, 0)
	for _, order := range result.Data {
		if order.CardID != "" {
			cardIDs = append(cardIDs, order.CardID)
		}
	}

	// 从数据库中查询卡片昵称
	var cards []models.UserCard
	if err := database.DB.Where("card_id IN ?", cardIDs).Find(&cards).Error; err != nil {
		return nil, fmt.Errorf("query card nicknames failed: %v", err)
	}

	// 创建卡片ID到昵称的映射
	cardNicknames := make(map[string]string)
	for _, card := range cards {
		cardNicknames[card.CardID] = card.NikeName
	}

	// 为每个订单添加卡片昵称
	for i := range result.Data {
		if nickname, exists := cardNicknames[result.Data[i].CardID]; exists {
			result.Data[i].CardNickname = nickname
		}
	}

	return &result, nil
}
